package com.tang.service.engine;


import com.tang.constance.NodeConstance;
import com.tang.entity.CarInfo;
import com.tang.model.aggregates.TreeRich;
import com.tang.model.vo.EngineResult;
import com.tang.model.vo.TreeNode;
import com.tang.model.vo.TreeRoot;
import com.tang.service.logic.LogicFilter;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * 规则执行抽象类，用于定义公共的方法
 *
 * @author fulin.tang
 */
@Slf4j
public abstract class EngineBase extends EngineConfig implements IEngine {


    @Override
    public abstract EngineResult process(Long treeId, String userId, TreeRich treeRich, CarInfo carInfo);

    /**
     * 关键类，用于获取最终的果实节点
     *
     * @param treeRich 树信息
     * @param treeId   树id
     * @param userId   用户id
     * @param carInfo  车辆信息
     * @return 最终的结果节点
     */
    protected TreeNode engineDecisionMaker(TreeRich treeRich, Long treeId, String userId, CarInfo carInfo) {
        // 链表啊
        TreeRoot treeRoot = treeRich.getTreeRoot();
        Map<Long, TreeNode> treeNodeMap = treeRich.getTreeNodeMap();
        // 规则树根ID
        Long rootNodeId = treeRoot.getTreeRootNodeId();
        TreeNode treeNodeInfo = treeNodeMap.get(rootNodeId);
        //节点类型[NodeType]；1子叶、2果实
        while (treeNodeInfo.getNodeType().equals(NodeConstance.NODE)) {
            // 通过判定条件获取对应的filter
            String ruleKey = treeNodeInfo.getRuleKey();
            LogicFilter logicFilter = logicFilterMap.get(ruleKey);
            // 通过对应filter获取传入的值
            Object matterValue = logicFilter.matterValue(treeId, userId, carInfo);
            // 找出下一个节点
            Long nextNode = logicFilter.filter(matterValue, treeNodeInfo.getTreeNodeLinkList());
            treeNodeInfo = treeNodeMap.get(nextNode);
            log.info("决策树引擎=>{} userId：{} treeId：{} treeNode：{} ruleKey：{} matterValue：{}", treeRoot.getTreeName(), userId, treeId, treeNodeInfo.getTreeNodeId(), ruleKey, matterValue);
        }
        return treeNodeInfo;
    }

}
